//index.js
//获取应用实例
var app = getApp()
var network = require("../../utils/network.js")
const pagesize = '20'

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    scrollViewHeith:350,
    // banner
    duration: 2000,
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    banner: [],
    imageHeight: 0,

    // 底部弹出
    dialogvisible: false,
    options: {
      showclose: true,
      showfooter: false,
      closeonclickmodal: true,
      fullscreen: false
    },
    title: '选择城市',
    opacity: '0.4',
    width: '100',
    position: 'bottom',

    cityList: [],
    curCity: {
      oid: '',
      name: '选择城市'
    },
    weather: '-',

    currentTab: 1,
    stallsList: [],
    stallsList2: [],
      // {
      //   oid: '',
      //   areaOid: '',
      //   image: '',
      //   title: '矿泉街',
      //   address: '越秀区矿泉街沙涌南洪阴围13号',
      //   attribute: ['零售水果', '小百货', '干果类'],
      //   distance: 2,
      //   fee: "20元/日",
      //   longitude: 113.258062,
      //   latitude: 23.153463,
      //   openTime: "20:00-02:00"
      // }
    curStallPage: 0,
    curLocation: {},
    stallPage1: 1,
    stallPage2: 1,
    // 最后拉取结果，有数据就true
    lastPullRes1: true,
    lastPullRes2: true,
    stallLoading1: false,
    stallLoading2: false,
  },

  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  onLoad: function () {
    var height = 40 + 150 + 60 + 54
    var windowHeight = app.globalData.phoneInfo.windowHeight
    this.setData({
      scrollViewHeith: windowHeight - height
    })
  },

  onShow: function() {
    this.getBanners()
    this.getCitys()
    this.getUserLocation()

    this.refreshStalls()
  },

  refreshStalls() {
    this.data.lastPullRes1 = true
    this.data.stallPage1 = 1
    this.data.stallsList = []
    this.getStalls()

    this.data.lastPullRes2 = true
    this.data.stallPage2 = 1
    this.data.stallsList2 = []
    this.getStalls2()
  },

  // 弹出底部窗口
  showCitys: function () {
    this.setData({
      dialogvisible: true
    })
  },

  handleOpen() {

  },

   // 弹出关闭
  handleClose: function () {
   
  },

  changeCity: function (e) {
    var item = e.currentTarget.dataset.item;
    this.setData({
      curCity: item,
      dialogvisible: false
    })

    this.refreshStalls()
    this.getWeahter()
  },

  getWeahter() {
    var that = this;
    network.request({
      url: '/sailclient/area/weather',
      data: {
        city: this.data.curCity.name
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' 
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        // console.log('天气',res)
        var weather = res.data.data
        var weatherStr = weather.temperature + '℃/' + weather.info + '/' + weather.direct + weather.wid + '级'
        that.setData({
          weather: weatherStr
        })
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  changeTab: function(e) {
    var that = this;
    var id = e.target.id;
    if (id == "tab1" && this.data.currentTab != 1) {
      that.setData({
        currentTab: 1
      })
      if (this.data.stallsList.length == 0) {
        this.getStalls()
      }
    } else if (id == "tab2" && this.data.currentTab != 2) {
      that.setData({
        currentTab: 2
      })
      if (this.data.stallsList2.length == 0) {
        this.getStalls2()
      }
    }
  },

  getBanners() {
    var that = this;
    network.request({
      url: '/sailclient/banner/search',
      data: {
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' 
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        // console.log('轮播图',res)
        var height = 150
        that.setData({
          imageHeight: height,
          banner: res.data.data
        })
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  // 用户定位授权
  getUserLocation() {
    let that = this
    wx.getSetting({
        success: (res) => {
            // 拒绝授权后再次进入重新授权
            if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
                wx.showModal({
                    title: '',
                    content: '【摆摊儿】需要获取你的地理位置，请确认授权',
                    success: function (res) {
                        if (res.cancel) {
                            wx.showToast({
                                title: '拒绝授权',
                                icon: 'none'
                            })
                            setTimeout(() => {
                              wx.navigateBack()
                          }, 1500)
                        } else if (res.confirm) {
                            wx.openSetting({
                                success: function (dataAu) {
                                    // console.log('dataAu:success', dataAu)
                                    if (dataAu.authSetting["scope.userLocation"] == true) {
                                        //再次授权，调用wx.getLocation的API
                                        that.getLocation(dataAu)
                                    } else {
                                        wx.showToast({
                                            title: '授权失败',
                                            icon: 'none'
                                        })
                                        setTimeout(() => {
                                            wx.navigateBack()
                                        }, 1500)
                                    }
                                }
                            })
                        }
                    }
                })
            }
            // 初始化进入，未授权
            else if (res.authSetting['scope.userLocation'] == undefined) {
                that.getLocation(res)
            }
            // 已授权
            else if (res.authSetting['scope.userLocation']) {
                that.getLocation(res)
            }
        }
    })
},

// 微信获得经纬度
getLocation(userLocation) {
    let that = this
    wx.getLocation({
        type: "wgs84",
        success: function (res) {
            // console.log('getLocation:success', res)
            var latitude = res.latitude
            var longitude = res.longitude
            that.data.curLocation = {
              lat: latitude,
              long: longitude
            }

            that.getStalls()
        },
        fail: function (res) {
            // console.log('getLocation:fail', res)
            if (res.errMsg === 'getLocation:fail:auth denied') {
                wx.showToast({
                    title: '拒绝授权',
                    icon: 'none'
                })
                setTimeout(() => {
                    wx.navigateBack()
                }, 1500)
                return
            }
            if (!userLocation || !userLocation.authSetting['scope.userLocation']) {
                vm.getUserLocation()
            } else if (userLocation.authSetting['scope.userLocation']) {
                wx.showModal({
                    title: '',
                    content: '请在系统设置中打开定位服务',
                    showCancel: false,
                    success: result => {
                        if (result.confirm) {
                            wx.navigateBack()
                        }
                    }
                })
            } else {
                wx.showToast({
                    title: '授权失败',
                    icon: 'none'
                })
                setTimeout(() => {
                    wx.navigateBack()
                }, 1500)
            }
        }
    })
  },

  // 请求地址
  getCitys() {
    var that = this;
    network.request({
      url: '/sailclient/area/search',
      data: {
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' 
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        // console.log('城市列表', res.data)
        that.setData({
          cityList: res.data.rows
        })
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  // 请求推荐摊点
  getStalls() {
    if (this.data.stallLoading1) {
      return
    }

    const latitude = this.data.curLocation.lat
    const longitude = this.data.curLocation.long
    if (latitude == undefined || latitude == null) {
      return
    }

    this.data.stallLoading1 = true
    var that = this;
    network.request({
      url: '/sailclient/stall/search/recommend',
      data: {
        latitude: latitude,
        longitude: longitude,
        size: pagesize,
        page: this.data.stallPage1,
        areaOid: this.data.curCity.oid,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' 
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        console.log('摊点', res)
        that.data.stallLoading1 = false
        if (res.data.rows) {
          that.data.stallPage1 = that.data.stallPage1 + 1
          var arr = that.data.stallsList.concat(res.data.rows)
          that.setData({
            stallsList: arr
          })

          if (res.data.rows.length < 20) {
            that.data.lastPullRes1 = false
          } else {
            that.data.lastPullRes1 = true
          }

          if (that.data.stallsList.length < 20) {
            that.data.stallPage1 = 1
          }
        } 

        if (that.data.stallPage1 > 1) {
          if (!res.data.rows || res.data.rows.length < 20) {
            that.data.lastPullRes1 = false
          } else {
            that.data.lastPullRes1 = true
          }
        }
      },
      fail: function (res) {
        that.data.stallLoading1 = false
      },
      complete: function (res) { },
    })
  },

  // 请求附近摊点
  getStalls2() {
    if (this.data.stallLoading2) {
      return
    }

    const latitude = this.data.curLocation.lat
    const longitude = this.data.curLocation.long
    if (latitude == undefined || latitude == null) {
       return
    }

    this.data.stallLoading2 = true
    var that = this;
    network.request({
      url: '/sailclient/stall/search',
      data: {
        latitude: latitude,
        longitude: longitude,
        size: pagesize,
        page: this.data.stallPage2,
        areaOid: this.data.curCity.oid,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' 
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        // console.log('摊点2',res)
        that.data.stallLoading2 = false
        if (res.data.rows) {
          that.data.stallPage2 = that.data.stallPage2 + 1
          var arr = that.data.stallsList2.concat(res.data.rows)
          that.setData({
            stallsList2: arr
          })

          if (res.data.rows.length < 20) {
            that.data.lastPullRes2 = false
          } else {
            that.data.lastPullRes2 = true
          }

          if (that.data.stallsList2.length < 20) {
            that.data.stallPage2 = 1
          }
        } 

        if (that.data.stallPage2 > 1) {
          if (!res.data.rows || res.data.rows.length < 20) {
            that.data.lastPullRes2 = false
          } else {
            that.data.lastPullRes2 = true
          }
        }
      },
      fail: function (res) { 
        that.data.stallLoading2 = false
      },
      complete: function (res) { },
    })
  },

  // 查看摊点详情
  viewDetail(e) {
    var oid = e.currentTarget.dataset.oid
    wx.navigateTo({
      url: '/pages/stallDetail/stallDetail?oid=' + oid,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  navToStall(e) {
    var item = e.currentTarget.dataset.item
    const latitude = item.latitude
    const longitude = item.longitude
    wx.openLocation({
      latitude,
      longitude,
      scale: 18
    })
  },

  // 上拉加载
  pullRefresh: function() {
    console.log("页面上拉触底事件的处理函数")
    if ((this.data.currentTab == 1 && !this.data.lastPullRes1) ||
      (this.data.currentTab == 2 && !this.data.lastPullRes2)) {
      wx.stopPullDownRefresh();
      return
    }

    if (this.data.currentTab == 1) {
      this.getStalls()
    } else {
      this.getStalls2()
    }
  },

  // 下拉刷新
  dropdownRefresh() {
    // console.log("页面下拉触底事件的处理函数")
    // if (this.data.currentTab == 1) {
    //   this.data.lastPullRes1 = true
    //   this.data.stallPage1 = 1
    //   this.getStalls()
    // } else {
    //   this.data.lastPullRes2 = true
    //   this.data.stallPage2 = 1
    //   this.getStalls2()
    // }
  },
})
